<?php
/**
 * 数据字典管理
 */

namespace support;

use app\common\model\Country;
use app\common\model\Member;
use app\common\model\MemberGroup;
use component\TableCache;

class Dictionary extends TableCache
{
    public static $table = 'dictionary';

    // static 和 self 的区别：
    // static:使用调用类的静态方法
    // self:在哪一个类中使用self就是用这个类的静态方法

    // 数据转化
    public static function convert($dictType, $key) {
        return static::get($dictType, $key);
    }

    // 键值获取
    public static function key($dictType, $val) {
        $all = static::get($dictType);
        return array_search($val, $all);
    }

    // 获取一类
    public static function get($dictType)
    {
        $all = static::all();
        $config = [];
        switch ($dictType) {
            case 'country':
                $config = (new Country())->dictGet();
                break;
            case 'country_id_code':
                $config = (new Country())->dictIDCodeGet();
                break;
            case 'country_id_hs_code':
                $config = (new Country())->dictIDHSCodeGet();
                break;
            case 'country_id_icon':
                $config = (new Country())->dictIDIconGet();
                break;
            case 'trade_mode':
                $config = config('trade_mode');
                break;
            case 'member_name':
                $config = (new Member())->dictGet();
                break;
            case 'member_name_mobile':
                $config = (new Member())->dictNameMobileGet();
                break;
            case 'member_name_id':
                $config = (new Member())->dictGet('member_id', 'member_name');
                break;
            case 'member_group':
                $config = (new MemberGroup())->dictGroupGet();
                break;
            case 'member_type':
                $config = (new MemberGroup())->dictTypeGet();
                break;
            default:
                $config = isset($all[$dictType]) ? $all[$dictType] : array();
        }
        if(func_num_args() == 1) {
            return $config;
        }
        $key = func_get_arg(1);

        return isset($config[$key]) ? $config[$key] : '';
    }

    // 数据格式化
    public static function format($list)
    {
        $_list = [];
        foreach ($list as $val) {
            $_list[$val['dict_type']][$val['key']] = $val['value'];
        }
        return $_list;
    }
}
